using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Expression.Dev.Dao;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.Expression.SPI;
using T.FAS.Runtime.Base.Entity;

namespace T.FAS.Runtime.Expression.Service
{
    class AdapterCache
    {
        private Dictionary<string, IDynamicActionAdapter> dynamicActionAdapters = null;
        private static readonly object syncObject = new object ();
        private static AdapterCache instance;
        private AdapterCache()
        {
            dynamicActionAdapters = new Dictionary<string, IDynamicActionAdapter>();
            InitIDynamicActionAdapter();
        }

        public static AdapterCache GetInstance()
        {
            if (instance == null)
            {
                lock (syncObject)
                {
                    if (instance == null)
                        instance = new AdapterCache();
                }
            }

            return instance;
        }

        public Dictionary<string, IDynamicActionAdapter> GetIDynamicActionAdapters() => dynamicActionAdapters;
        private void InitIDynamicActionAdapter()
        {
            var exprMetaDataDao = new ExprMetaDataDao();
            var exprMetaDatas = exprMetaDataDao.GetExprMetaDataList();
            if (exprMetaDatas == null)
                throw new FasException(ExprExceptionCode.GetExprMetaDataListFailed, $"{T.ServiceComponent.I18N.Service.TermService.Current.GetText("T_FAS_fasr_Expression_317164174", "获取表达式元数据失败！")}");
            Dictionary<string, IDynamicActionAdapter> dynamicAdapters = new Dictionary<string, IDynamicActionAdapter>();
            foreach (var item in exprMetaDatas)
            {
                if (!string.IsNullOrEmpty(item.Executor))
                {
                    try
                    {
                        Type o = Type.GetType(item.Executor);
                        IDynamicActionAdapter executor = Activator.CreateInstance(o, true) as IDynamicActionAdapter;
                        dynamicAdapters[item.Name] = executor;
                    }
                    catch (Exception e)
                    {
                        Base.Common.LogUtil.Log(e.ToString(), "ExprError");
                    }
                }
            }

            dynamicActionAdapters = dynamicAdapters;
        }
    }
}